package com.mopencode.seckill.service.impl;

import com.lxs.legou.common.utils.SystemConstants;
import com.lxs.legou.core.service.impl.CrudServiceImpl;
import com.mopencode.seckill.po.SeckillOrder;
import com.mopencode.seckill.pojo.SeckillStatus;
import com.mopencode.seckill.service.SeckillOrderService;
import com.mopencode.seckill.task.MultiThreadingCreateOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Mcb
 * @date 2022/4/9
 * @apiNote
 */
@Service
public class SeckillOrderServiceImpl extends CrudServiceImpl<SeckillOrder> implements SeckillOrderService {

    @Autowired
    private MultiThreadingCreateOrder orderTask;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean addOrder(String userId, String time, int goodsId) {
        //防止重复秒杀
        Long payCount = redisTemplate.boundHashOps(SystemConstants.SEC_KILL_QUEUE_REPEAT_KEY).increment(userId, 1);
        if (payCount > 1) {
            throw new RuntimeException("秒杀商品不可重复购买");
        }

        SeckillStatus seckillStatus = new SeckillStatus(userId, new Date(), 1, goodsId, time);
        //顺序排队
        redisTemplate.boundListOps(SystemConstants.SEC_KILL_USER_QUEUE_KEY).leftPush(seckillStatus);

        orderTask.createOrder();

        return true;
    }
}
